﻿using Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Google.Protobuf;

namespace Network
{
    public class NetConnection
    {
        public delegate void DataReceivedCallback(NetConnection sender, byte[] data);
        public delegate void DisconnectedCallback(NetConnection sender);

        public Socket socket;

        DataReceivedCallback dataReceivedCallback;
        DisconnectedCallback disconnectedCallback;

        public NetConnection(Socket socket, DataReceivedCallback dataReceivedCallback, DisconnectedCallback disconnectedCallback)
        {
            this.socket = socket;
            this.dataReceivedCallback = dataReceivedCallback;
            this.disconnectedCallback = disconnectedCallback;

            // 创建解码器
            LengthFieldDecoder decoder = new LengthFieldDecoder(socket, 64 * 1024, 0, 4, 0, 4);
            decoder.dataReceivedHandler += OnDataReceived;
            decoder.disconnectedHandler += () => disconnectedCallback(this);
            decoder.Start();
        }

        private void OnDataReceived(object? sender, byte[] e)
        {
            dataReceivedCallback?.Invoke(this, e);
        }


        public void Close()
        {
            try { socket.Shutdown(SocketShutdown.Both); } catch {  }
            disconnectedCallback?.Invoke(this);
            socket.Close();
            socket = null;
          
        }

    }
}
